﻿Option Strict On
Option Explicit On
Imports AuthorizeNet
Imports System.Globalization

Partial Class private_secure_members_manage_MyCredit
    Inherits System.Web.UI.Page

    Dim u As MembershipUser
    Dim personId As Int32
    Dim delid As Integer
    Dim entityid As Integer

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        u = Membership.GetUser(HttpContext.Current.User.Identity.Name)

        Dim getpersonid As New GetPersonIdFromUserId()

        personId = getpersonid.GetPersonId(CType(u.ProviderUserKey, Guid))
        Dim entityidTA As New LogginsLogDSTableAdapters.usp_GetEntityListFull_ByPersonIdTableAdapter()
        Dim entityidDT As LogginsLogDS.usp_GetEntityListFull_ByPersonIdDataTable
        entityidDT = entityidTA.GetData(personId)

        Try
            GridView1.DataBind()
        Catch ex As Exception

        End Try
        If Not Page.IsPostBack Then


            txtCardNumber.Text = "4111111111111111"
            txtCVV.Text = "0116"
            ExpDateTxtBox.Text = "123"
        End If
    End Sub
    Protected Sub SqlEntity_ds_Selecting(sender As Object, e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles SqlEntity_ds.Selecting
        e.Command.Parameters("@PersonId").Value = CType(personId, Integer)
    End Sub

    Protected Sub btnBuyCredit_Click(sender As Object, e As System.EventArgs) Handles btnBuyCredit.Click
        'Because the user is paying money make sure that no one else is spending money on their behalf
        'So ask them for their credentials again even though they are logged in

        'Now pop up a box allowing the user to purchase credits - 10, 20, 50, 100, 200, 500, 1000

    End Sub

    Protected Sub Button2_Click(sender As Object, e As System.EventArgs) Handles Button2.Click

        If CInt(lblSum.Text) <> 0 Then
            Label8.Text = "Select your credit card"
            ModalPopupExtender2.Show()
            MsgLbl.Text = String.Empty
            'If CheckCartNumber() AndAlso CheckExpDate() AndAlso CheckCVVNumber() Then
            '    ModalPopupExtender2.Show()
            'End If
        Else
            Label9.Text = ("Select one or more item from the list first.")
        End If
    End Sub
    Private Function OpenGateway() As IGateway
        Dim login = ConfigurationManager.AppSettings("ApiLogin")
        Dim transactionKey = ConfigurationManager.AppSettings("TransactionKey")

        Dim gate = New Gateway(login, transactionKey, True)
        Return gate
    End Function

    Private Function ExecutePayment(ByVal credits As String) As String
        Dim gate = OpenGateway()
        Dim apiRequest = CheckoutFormReaders.BuildAuthAndCaptureFromPost()

        Try
            Dim price As [String] = credits
            Dim cardNumber As [String] = txtCardNumber.Text
            Dim expDate As [String] = ExpDateTxtBox.Text
            'Dim expDate As [String] = cboCardExpiryMM.SelectedValue.ToString() + cboCardExpiryYY.DataValueField.ToString()
            Dim ccv As [String] = txtCVV.Text

            apiRequest.Queue(ApiFields.Amount, price)
            apiRequest.Queue(ApiFields.CreditCardNumber, cardNumber)
            apiRequest.Queue(ApiFields.CreditCardExpiration, expDate)
            apiRequest.Queue(ApiFields.CreditCardCode, ccv)
        Catch
            Return "error"
        End Try

        Dim response = gate.Send(apiRequest)

        If response.Approved Then

            Dim AuthCode As String = response.AuthorizationCode
            Dim TransactionID As String = response.TransactionID
            Dim OrderMessage As String = String.Format("Thank you! Order approved: {0}", response.AuthorizationCode)

            MsgLbl.Text = "Response message is: " & Convert.ToString(response.Message) & "</br>" & "Response code is: " & Convert.ToString(response.ResponseCode) & "</br>" & "TransactionID is: " & Convert.ToString(response.TransactionID)

            Return TransactionID
        Else
            Dim OrderMessage As String = response.Message
            MsgLbl.Text = "Response message is: " & Convert.ToString(response.Message) & "</br>" & "Response code is: " & Convert.ToString(response.ResponseCode)
            Return "error"
        End If
    End Function
    'Function FormatDecimalToCurrency(ByVal Value As Decimal) As String
    '    Dim nfi As NumberFormatInfo = New CultureInfo("en-AU", False).NumberFormat
    '    Dim num As Decimal = Decimal.Parse(CStr(Value))
    '    Return num.ToString("C", nfi)
    'End Function

    'Function ConvertStringToDecimal(ByVal Value As String) As String
    '    Dim cardnum As String = ""
    '    For Each chr As Char In Value
    '        If Char.IsNumber(chr) OrElse chr = "." Then
    '            cardnum += chr
    '        End If
    '    Next
    '    Return cardnum
    'End Function
    Function CheckCartNumber() As Boolean

        ' Validation not working
        'Return True

        Dim validation As Boolean
        Dim cardnum = txtCardNumber.Text
        'txtCardType1.Text = cardnum
        'cboCCType
        Dim selected = cboCCType.SelectedValue.ToString()
        If cardnum.Length > 0 Then
            If cardnum.Length > 4 Then
                Dim trimedtext As String = cardnum
                Dim trimedtext1 As String = trimedtext.Substring(0, 1)
                Dim trimedtext2 As String = trimedtext.Substring(0, 2)
                Dim trimedtext3 As String = trimedtext.Substring(0, 3)
                Dim trimedtext4 As String = trimedtext.Substring(0, 4)
                If selected = "1" Then
                    If CDbl(trimedtext1) = 4 Then
                        If trimedtext.Length = 13 OrElse trimedtext.Length = 16 Then
                            MsgLbl.Text = ("Visa is ok")

                            validation = True
                        Else
                            MsgLbl.Text = ("Visa is NOT ok")
                            validation = False
                        End If
                    Else
                        MsgLbl.Text = ("Visa number is NOT ok")
                    End If


                End If
                If selected = "2" Then
                    If CDbl(trimedtext2) = 36 OrElse CDbl(trimedtext2) = 51 OrElse CDbl(trimedtext2) = 52 OrElse CDbl(trimedtext2) = 53 OrElse CDbl(trimedtext2) = 54 OrElse CDbl(trimedtext2) = 55 Then
                        If trimedtext.Length = 14 OrElse trimedtext.Length = 16 Then
                            MsgLbl.Text = ("Mastercard is ok")
                            validation = True
                        Else
                            MsgLbl.Text = ("Mastercard is NOT ok")
                            validation = False
                        End If
                    Else
                        MsgLbl.Text = ("Mastercard number is NOT ok")
                    End If

                End If

            End If
        Else
            MsgLbl.Text = "Please enter valid cart number it must be more then 4 digits."
            validation = False
        End If
        Return validation
    End Function

    Function CheckExpDate() As Boolean
        Dim validation As Boolean
        If cboCardExpiryMM.SelectedItem IsNot Nothing AndAlso cboCardExpiryYY.SelectedItem IsNot Nothing Then
            Dim selectedmonth = cboCardExpiryMM.SelectedItem.ToString()
            Dim selectedyear = cboCardExpiryYY.SelectedItem.ToString()

            Dim currentmonth = Date.Today.Month
            Dim currentyear = Date.Today.Year

            'DateTime.Now.ToString("dd/MM/yyyy")
            If (currentyear - 2000).ToString() = selectedyear Then
                If Not currentmonth <= CInt(selectedmonth) Then
                    MsgLbl.Text = ("Cart expired")
                    validation = False
                Else
                    validation = True
                End If
            Else
                If currentmonth <= CInt(selectedmonth) AndAlso currentyear - 2000 <= CDbl(selectedyear) Then
                    validation = True
                Else
                    MsgLbl.Text = ("Cart expired")
                    validation = False
                End If
            End If




        Else
        End If


        Return validation

    End Function

    Function CheckCVVNumber() As Boolean
        Dim validation As Boolean
        Dim number As Integer
        Dim CVVnum As Boolean = Int32.TryParse(txtCVV.Text, number)
        If CVVnum Then
            If txtCVV.Text.Length = 4 Then

                If CVVnum Then
                    MsgLbl.Text = ("CVV has three numbers")
                    validation = True
                End If
            Else
                MsgLbl.Text = ("CVV must not be longer then three numbers")
                validation = False
            End If
        Else
            MsgLbl.Text = ("CVV has to be number")
            validation = False
        End If
        Return validation
    End Function

    Protected Sub CheckBoxList1_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles CheckBoxList1.SelectedIndexChanged
        lblSum.Text = "0"
        Dim i As Integer
        'Dim sum As Integer = 0
        For i = 0 To CheckBoxList1.Items.Count - 1

            If CheckBoxList1.Items(i).Selected Then

                lblSum.Text = (CInt(CheckBoxList1.Items(i).Value) + CInt(lblSum.Text)).ToString()
                'sum = (CInt(CheckBoxList1.Items(i).Value) + CInt(lblSum.Text))
            End If

        Next
        UpdatePanel1.Update()
    End Sub


    Protected Sub Button7_Click(sender As Object, e As System.EventArgs) Handles Button7.Click
        If CInt(lblSum.Text) <> 0 Then

            If CheckCartNumber() AndAlso CheckExpDate() AndAlso CheckCVVNumber() Then
                ExecutePayment(CInt(lblSum.Text).ToString())

            End If
        Else
            MsgLbl.Text = ("Close this window and select one or more item from the list first.")
        End If
        UpdatePanel2.Update()
    End Sub
End Class
